package com.example.demo.web.handler;

import com.alibaba.fastjson2.JSON;
import com.example.demo.constants.Constants;
import com.example.demo.domain.base.BaseResult;
import jdk.nashorn.internal.ir.debug.ObjectSizeCalculator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * ResponseBodyLogAdvice
 *
 * @author hao.chen
 * @date 2022/2/25 14:08
 */
@Slf4j
@RestControllerAdvice
public class ResponseBodyLogAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class converterType, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        HttpServletRequest request = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
        Long beginTime = (Long) request.getAttribute(Constants.BEGIN_TIME);
        if (body instanceof BaseResult || body instanceof JSON) {
            long useTime = System.currentTimeMillis() - beginTime;
            long sizeKB = ObjectSizeCalculator.getObjectSize(body) / 1024;
            if (sizeKB > 512) {
                log.info("Response << time: {} - data too large ({} KB), ignored for logging", useTime, sizeKB);
            } else {
                log.info("Response << time: {} - data: {}", useTime, JSON.toJSONString(body));
            }
        } else {
            long useTime = System.currentTimeMillis() - beginTime;
            log.info("Response << time: {}", useTime);
        }
        return body;
    }
}
